package com.zuul.leku.filter;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StreamUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import static com.netflix.zuul.context.RequestContext.getCurrentContext;



public class ResponseFilter extends ZuulFilter{
	
	public static final String KEY_ERROR = "hasError";
	
	@Override
	public Object run(){
		try {
			RequestContext context = getCurrentContext();

			InputStream stream = context.getResponseDataStream();
			String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
			context.setResponseBody("Modified via setResponseBody(): " + body);
			context.setResponseStatusCode(200);
		} catch (IOException e) {
			
		}
		return null;
	}

	@Override
	public boolean shouldFilter() {
		RequestContext context = getCurrentContext();
		// 有错误的返回不处理，其他请求都处理
		return null == context.get(KEY_ERROR);
	}

	@Override
	public String filterType() {
		return "post";
	}

	@Override
	public int filterOrder() {
		// TODO Auto-generated method stub
		return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
	}
}
